﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using Ashlen.Portal.Core;
using Ashlen.Portal.Core.DTO;
using Ashlen.Portal.Core.DataInterfaces;
using Ashlen.Portal.Data.SqlServer;

namespace Ashlen.Portal.Services.Handlers
{
    /// <summary>
    /// Summary description for UploadHandler
    /// </summary>
    public class UploadHandler : IHttpHandler
    {
        private readonly ISecurityDao _securityDao;
        private readonly IUtilityDao _utility;

        public UploadHandler()
        {
            _securityDao = new SecurityDao();
            _utility = new UtilityDao();
        }

        public void ProcessRequest(HttpContext context)
        {
            try
            {
                var strFileName = Path.GetFileName(context.Request.Files[0].FileName);
                var userGuid = context.Request.Params["UserGuid"];
                userGuid = (userGuid == null ? "temp" : userGuid);
                var strExtension = Path.GetExtension(context.Request.Files[0].FileName).ToLower();
                var sFolder = context.Server.MapPath("../upload") + @"\" + userGuid;
                var sLocation = sFolder + @"\" + strFileName;
                //var sLocation = sFolder + @"\Avatar" + Path.GetExtension(strFileName);

                try
                {
                    if (Directory.Exists(sFolder))
                    {
                        foreach (var file in Directory.GetFiles(sFolder))
                        {
                            try
                            {
                                File.Delete(file);
                            }
                            catch { }
                        }
                    }
                    else
                    {
                        Directory.CreateDirectory(sFolder);
                    }
                }
                catch { }
                context.Request.Files[0].SaveAs(sLocation);
                SaveImageToDB(userGuid, ReadFully(context.Request.Files[0].InputStream));
                context.Response.ContentType = "text/plain";
                context.Response.Write("OK");
            }
            catch (Exception ex)
            {
                context.Response.ContentType = "text/plain";
                context.Response.Write(ex.ToString());
            }
        }

        public static byte[] ReadFully(Stream input)
        {
            byte[] buffer = new byte[16 * 1024];
            using (MemoryStream ms = new MemoryStream())
            {
                int read;
                while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
                {
                    ms.Write(buffer, 0, read);
                }
                return ms.ToArray();
            }
        } 

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        private void SaveImageToDB(string userGuid, byte[] avatar)
        {
            if (userGuid != "temp" && userGuid != string.Empty)
            {
                var userId = new Guid(userGuid);
                _securityDao.SaveAvatar(userId, avatar);

            }
        }
    }
}